package utility;

public class Bytes2String {

	public static String byteArray2Binary(byte[] bytes){
		StringBuffer stringBuffer=new StringBuffer();
		for(int i=0;i<bytes.length;i++){
			String s=byte2Binary(bytes[i]);
			stringBuffer.append(s);
			stringBuffer.append("-");
		}
		stringBuffer.deleteCharAt(stringBuffer.length()-1);
		String resultString=stringBuffer.toString();
		return resultString;
	}
	
	public static String byte2Binary(byte b) {
		String s=Integer.toString( ( b & 0xff ), 2);
		s=addPrefix(s, 8);
		return s;
	}
	
	private static String addPrefix(String string,int standardLength){
		if(string==null){
			return null;
		}
		int i=standardLength-string.length();
		if(i<=0){
			return string;
		}
		StringBuffer stringBuffer=new StringBuffer();
		for(int j=0;j<i;j++){
			stringBuffer.append("0");
		}
		return string+stringBuffer.toString();
	}
	
	public static String byte2Hex(byte b){
		String s=Integer.toString( ( b & 0xff ), 16);
		s=addPrefix(s, 2);
		return s;
	}
	
	public static String byteArray2Hex(byte[] bytes){
		StringBuffer stringBuffer=new StringBuffer();
		for(int i=0;i<bytes.length;i++){
			String s=byte2Hex(bytes[i]);
			stringBuffer.append(s);
			stringBuffer.append("-");
		}
		stringBuffer.deleteCharAt(stringBuffer.length()-1);
		String resultString=stringBuffer.toString();
		return resultString;
	}
	
	
	public static void main(String[] args) {
		byte[] byteArray=new byte[256];
		for (int i = -128; i < 128; i++) {
			byte b=(byte)i;
			System.out.println( "b= "+b+" | "+Integer.toString( ( b & 0xff ), 2)+" | "+Integer.toString( ( b & 0xff ), 16));
			/*System.out.println( "b= "+b+" | "+Integer.toString(  (int)b  , 2)+" | "+Integer.toString(  b  , 16));
			String s=Integer.toString( ( b & 0xff ), 2);
			s=addPrefix(s, 8);
			System.out.println(s);*/
			System.out.println(byte2Binary(b));
			System.out.println(byte2Hex(b));
			byteArray[i+128]=b;
		}
		System.out.println("****************");
		System.out.println(byteArray2Binary(byteArray));
		System.out.println("****************");
		System.out.println(byteArray2Hex(byteArray));
	}
}
